<template>
  <xr-create :loading="loading" :title="title" @close="close" @save="saveClick">
    <create-sections title="基本信息">
      <wk-form
        ref="crmForm"
        :model="fieldForm"
        :rules="fieldRules"
        :field-from="fieldForm"
        :field-list="fieldList"
        label-position="top"
        @change="formChange"
      />
    </create-sections>
    <create-sections title="训练营" v-if="fieldList1 && fieldList1.length > 0">
      <wk-form
        ref="crmForm1"
        :model="fieldForm"
        :rules="fieldRules1"
        :field-from="fieldForm"
        :field-list="fieldList1"
        label-position="top"
        @change="formChange"
      />
    </create-sections>
    <create-sections
      title="系统信息"
      v-if="fieldList2 && fieldList2.length > 0"
    >
      <wk-form
        ref="crmForm2"
        :model="fieldForm"
        :rules="fieldRules2"
        :field-from="fieldForm"
        :field-list="fieldList2"
        label-position="top"
        @change="formChange"
      />
    </create-sections>
  </xr-create>
</template>

<script>
import { filedGetFieldAPI } from "@/api/crm/common";
import { crmLeadsSaveAPI } from "@/api/crm/leads";

import XrCreate from "@/components/XrCreate";
import CreateSections from "@/components/CreateSections";
import WkForm from "@/components/NewCom/WkForm";

import crmTypeModel from "@/views/crm/model/crmTypeModel";
import CustomFieldsMixin from "@/mixins/CustomFields";
import { isEmpty } from "@/utils/types";
import { mapGetters } from "vuex";
export default {
  // 新建编辑
  name: "LeadsCreate",

  components: {
    XrCreate,
    CreateSections,
    WkForm,
  },

  mixins: [CustomFieldsMixin],

  props: {
    phone: String,
    action: {
      type: Object,
      default: () => {
        return {
          type: "save",
          id: "",
          data: {},
        };
      },
    },
  },

  data() {
    return {
      loading: false,
      baseFields: [],
      fieldList: [],
      fieldList1: [],
      fieldList2: [],
      fieldForm: {},
      fieldRules: {},
      fieldRules1: {},
      fieldRules2: {},
    };
  },

  computed: {
    ...mapGetters(["userInfo"]),
    title() {
      return this.action.type === "update" ? "编辑线索" : "新建线索";
    },
  },

  watch: {},

  created() {
    this.getField();
  },

  mounted() {},

  beforeDestroy() {},

  methods: {
    /**
     * 获取数据
     */
    getField() {
      this.loading = true;
      const params = {
        label: crmTypeModel.leads,
      };

      if (this.action.type == "update") {
        params.id = this.action.id;
      }

      filedGetFieldAPI(params)
        .then((res) => {
          const list = res.data || [];
          if (!isEmpty(this.phone)) {
            list.forEach((item) => {
              if (item.formType === "mobile") {
                item.defaultValue = this.phone;
              }
            });
          }

          const fieldList = [];
          const fieldList1 = [];
          const fieldList2 = [];
          const fieldRules = {};
          const fieldRules1 = {};
          const fieldRules2 = {};
          const fieldForm = {};
          list.forEach((item) => {
            const temp = {};
            temp.field = item.fieldName;
            temp.formType = item.formType;
            temp.fieldId = item.fieldId;
            temp.inputTips = item.inputTips;
            temp.name = item.name;
            temp.setting = item.setting;
            temp.levelData = item.levelData;
            temp.restrictData = item.restrictData;
            temp.displayShow = true;
            if (item.formType === "select") {
              if (item.authLevel == 1) {
                temp.displayShow = true;
                temp.isNull = 0;
              } else {
                temp.displayShow = true;
              }
            }

            if (item.fieldName === "telephone") {
              temp.maxlength = item.maxLength;
            } else if (item.fieldName === "trainingPeriods") {
              temp.maxlength = item.maxLength;
            }

            if (temp.fieldId == 1102117) {
              //销售类型回显
              let arr = [];
              for (let i = 0; i < item.setting.length; i++) {
                const obj = {
                  label: item.setting[i],
                  value: i + 1,
                };
                arr.push(obj);
              }
              temp.setting = arr;
            }

            if (temp.formType == "single_user") {
              if (temp.field == "teacherId") {
                temp.isTeacher = true;
              } else {
                temp.isTeacher = false;
              }
            }

            const canEdit = this.getItemIsCanEdit(item, this.action.type);
            // 是否能编辑权限
            if (canEdit) {
              if (item.fieldName == "trainingPeriods") {
                fieldRules1[temp.field] = this.getRules(item);
              } else if (
                item.fieldName == "ownerUserId" ||
                item.fieldId == 1101914
              ) {
                fieldRules2[temp.field] = this.getRules(item);
              } else {
                fieldRules[temp.field] = this.getRules(item);
              }
            }

            // 是否可编辑
            temp.disabled = !canEdit;

            // 特殊字段允许多选
            this.getItemRadio(item, temp);
            fieldForm[temp.field] = this.getItemValue(
              item,
              this.action.data,
              this.action.type
            );
            if (this.action.type != "update") {
              if (item.fieldName == "leadsUserId") {
                fieldForm["leadsUserId"] = this.userInfo.userId;
              }
            }

            // 获取默认值
            if (item.fieldName == "trainingPeriods") {
              fieldList1.push(temp);
            } else if (
              item.fieldName == "ownerUserId" ||
              item.fieldId == 1101914
            ) {
              fieldList2.push(temp);
            } else {
              if (item.formType === "select") {
                if (item.authLevel == 1) {
                  temp.displayShow = true;
                  temp.isNull = 0;
                } else {
                  fieldList.push(temp);
                }
              } else {
                fieldList.push(temp);
              }
            }
          });
          this.baseFields = list;
          this.fieldList = fieldList;
          this.fieldList1 = fieldList1;
          this.fieldList2 = fieldList2;
          this.fieldForm = fieldForm;
          // console.log(this.fieldForm,2222,fieldRules,fieldRules1,fieldRules2)
          this.fieldRules = fieldRules;
          this.fieldRules1 = fieldRules1;
          this.fieldRules2 = fieldRules2;
          this.loading = false;
        })
        .catch(() => {
          this.loading = false;
        });
    },

    /**
     * 保存
     */
    saveClick() {
      this.loading = true;
      const crmForm = this.$refs.crmForm.instance;
      let submitData = () => {
        const params = this.getSubmiteParams(this.baseFields, this.fieldForm);
        this.submiteParams(params);
      };
      crmForm.validate((valid) => {
        if (valid) {
          if (this.fieldList1 && this.fieldList1.length > 0) {
            const crmForm1 = this.$refs.crmForm1.instance;
            crmForm1.validate((valid1) => {
              if (valid1) {
                submitData();
              } else {
                this.loading = false;
                // 提示第一个error
                this.getFormErrorMessage(crmForm);
                return false;
              }
            });
          } else {
            submitData();
          }
        } else {
          this.loading = false;
          // 提示第一个error
          this.getFormErrorMessage(crmForm);
          return false;
        }
      });
    },

    /**
     * 提交上传
     */
    submiteParams(params) {
      if (this.action.type == "update") {
        params.entity.leadsId = this.action.id;
        params.entity.batchId = this.action.batchId;
      }

      // 相关添加时候的多余提交信息
      if (
        this.action.relativeData &&
        Object.keys(this.action.relativeData).length
      ) {
        params = { ...params, ...this.action.relativeData };
      }
      crmLeadsSaveAPI(params)
        .then((res) => {
          this.loading = false;
          this.$message.success(
            this.action.type == "update" ? "编辑成功" : "添加成功"
          );

          this.close();

          // 保存成功
          this.$emit("save-success", {
            type: "leads",
          });
        })
        .catch(() => {
          this.loading = false;
        });
    },

    /**
     * 验证唯一
     */
    UniquePromise({ field, value }) {
      return this.getUniquePromise(field, value, this.action);
    },

    /**
     * change
     */
    formChange(item, index, value, valueList) {
      if (item.fieldId == 1101908) {
        //是否加微信
        this.fieldList[6].disabled = !(value == "是");
        this.fieldList[7].disabled = !(value == "是");
      }
    },

    /**
     * 地址change
     */
    otherChange(data, field) {
      this.$set(this.fieldForm, field.field, data.value);
      this.$refs.crmForm.instance.validateField(field.field);
    },

    /**
     * 关闭
     */
    close() {
      this.$emit("close");
    },
  },
};
</script>

<style lang="scss" scoped></style>
